﻿using System;
using System.IO;
using System.Threading;
using System.Windows.Forms;

namespace EasyIot.WinApp
{
    public class LogHelper
    {
        static string m_strFolder = Application.StartupPath + "\\log";

        /// <summary>
        /// 捕获未处理的异常
        /// </summary>
        public static void StartCatchAppException()
        {
            Application.ThreadException += new ThreadExceptionEventHandler(ApplicationExceptionFunc);
        }
        
        /// <summary>
        /// 捕获未处理的异常
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void ApplicationExceptionFunc(object sender, ThreadExceptionEventArgs e)
        {
            string str = string.Empty;
            string strDateInfo = "出现应用程序未处理的异常：" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n";

            if (e.Exception != null)
            {
                str = string.Format(strDateInfo + "异常类型：{0}\r\n异常消息：{1}\r\n异常信息：{2}\r\n",
                     e.Exception.GetType().Name, e.Exception.Message, e.Exception.StackTrace);
            }
            else
            {
                str = string.Format("应用程序线程错误:{0}", e.Exception);
            }
            AppendLog("异常退出:" + str, "");
        }

        /// <summary>
        /// txt文件记录
        /// </summary>
        /// <param name="fileType"></param>
        /// <param name="value"></param>
        public static void AppendLog(string value, string filename = "log")
        {
            if (string.IsNullOrEmpty(filename)) filename = "error";

            value = "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] " + value + Environment.NewLine;

            Console.WriteLine(value);
 
            try
            {
                if (!Directory.Exists(m_strFolder))
                {
                    Directory.CreateDirectory(m_strFolder);
                }
                string strPath = m_strFolder + "\\" + filename + "(" + DateTime.Now.ToString("yyyy-MM-dd") + ").txt";
                FileStream fsW = new FileStream(strPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                StreamWriter sw = new StreamWriter(fsW);
                sw.WriteLine(value);
                sw.Flush();
                fsW.Flush();
                sw.Close();
                fsW.Close();
                sw.Dispose();
                fsW.Dispose();
            }
            catch { }
        }
    }
}
